package org.wmine.core;

import java.io.*;
import java.util.*;
import java.util.List;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import java.awt.event.*;

import org.wmine.data.*;

public class CSVReader extends AbstractDataReader 
{
	Table sampleTable=new Table();

	static String filePath;
	ArrayList<Attribute> attributeList=new ArrayList<Attribute>();
	ArrayList<Tuple> tupleList=new ArrayList<Tuple>();
	
	
	public CSVReader(String filePath)
	{
		System.out.print("csv const");
		this.filePath=filePath;
		CSV csv=new CSV();
		try
		{
			process(csv, new BufferedReader(new FileReader(filePath)));
			//getTableValue();
		}catch(IOException ee) {}
	}
	/*public static void main(String args[]) throws IOException,FileNotFoundException
	{
		CSVReader cr=new CSVReader("C:\\CSV.dat");
		System.out.println(filePath);
		CSV csv=new CSV();
		cr.process(csv, new BufferedReader(new FileReader(filePath)));
		
		
	}*/
	public void process(CSV csv,BufferedReader is) throws IOException
	{
		String line,iteratorElement=null;
		int noOfTuples=0,lineNo=0,noOfAttributes=0;
		while((line=is.readLine())!=null)
		{
			Iterator e=csv.parse(line).iterator();
			ArrayList<String> singleTupleCollection=new ArrayList<String>();
			while(e.hasNext())
			{
				iteratorElement=(String) e.next();
            	if(lineNo==0)
      			{ 
      	  			Attribute singleAttribute=new Attribute();
      	  			singleAttribute.setAttributeName(iteratorElement);
      	  			singleAttribute.setAttributeType("string");
      	  			attributeList.add(singleAttribute);
      	  			noOfAttributes++;
      				//System.out.println("::: "+ iteratorElement);
        		}
        		else
        		{
        		    singleTupleCollection.add(iteratorElement);
            		//System.out.println("ob"+iteratorElement);
                }
        	}
        	lineNo++;
        	sampleTable.setAttributeList(attributeList);
      		Tuple singleTuple = new Tuple();
	        singleTuple.setTupleValuesList(singleTupleCollection);
            tupleList.add(singleTuple);   
            noOfTuples++;
        }
		
		sampleTable.setNameTable("FileCSV");
        sampleTable.setTupleList(tupleList);
        sampleTable.setNoOfTuples(noOfTuples-1);
        sampleTable.setNoOfAttributes(noOfAttributes);
    }
    /*public void getTableValue()
    {
    	System.out.println("gettableval"+sampleTable.getNoOfAttributes());
    }*/
	public Table getTable()
	{
		return sampleTable;
	}
}

class CSV {  

  public static final char DEFAULT_SEP = ',';

  /** Construct a CSV parser, with the default separator (`,'). */
  public CSV() 
  {
    this(DEFAULT_SEP);
  }

  /** Construct a CSV parser with a given separator. 
   * @param sep The single char for the separator (not a list of
   * separator characters)
   */
  public CSV(char sep) 
  {
    fieldSep = sep;
  }

  /** The fields in the current String */
  protected List list = new ArrayList();

  /** the separator char for this parser */
  protected char fieldSep;

  /** parse: break the input String into fields
   * @return java.util.Iterator containing each field 
   * from the original as a String, in order.
   */
  public List parse(String line)
  {
  	StringBuffer sb = new StringBuffer();
    list.clear();      // recycle to initial state
    int i = 0;

    if (line.length() == 0) 
    {
      list.add(line);
      return list;
    }

    do 
    {
            sb.setLength(0);
            if (i < line.length() && line.charAt(i) == '"')
                i = advQuoted(line, sb, ++i);  // skip quote
            else
                i = advPlain(line, sb, i);
            list.add(sb.toString());
      i++;
    } while (i < line.length()-1);

    return list;
  }

  /** advQuoted: quoted field; return index of next separator */
  protected int advQuoted(String s, StringBuffer sb, int i)
  {
    int j;
    int len= s.length();
    //System.out.println("Length of attrib="+len);
        for (j=i; j<len; j++) 
        {
            if (s.charAt(j) == '"' && j+1 < len) 
            {
            	
                if (s.charAt(j+1) == '"') 
                {
                    j++; // skip escape char
                } else if (s.charAt(j+1) == fieldSep) 
                { //next delimeter
                    j++; // skip end quotes
                    break;
                }
            } 
            else if (s.charAt(j) == '"' && j+1 == len) 
            { // end quotes at end of line
                break; //done
      		}
      		sb.append(s.charAt(j));  // regular character.
    	}
    	return j;
  	}

  /** advPlain: unquoted field; return index of next separator */
  protected int advPlain(String s, StringBuffer sb, int i)
  {
    int j;

    j = s.indexOf(fieldSep, i); // look for separator
        if (j == -1) 
        {                 // none found
            sb.append(s.substring(i));
            return s.length();
        } 
        else 
        {
            sb.append(s.substring(i, j));
            return j;
        }
    }
}
		
